package com.ineatconseil.yougo.pages.requests.list;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;

import com.ineatconseil.yougo.beans.ActionType;
import com.ineatconseil.yougo.beans.Request;
import com.ineatconseil.yougo.dto.RequestDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.pages.AbstractPage;
import com.ineatconseil.yougo.services.rest.RestPath;
import com.sun.jersey.api.client.GenericType;

public class RequestsList extends AbstractPage {

	@SuppressWarnings("unused")
	@Property
	private Request request;

	/**
	 * Get the requests list.
	 */
	public List<Request> getRequests() {

		try {

			List<RestPath> paths =
					RestPath.getSimplePath(RestPath.PATH_USERS, String.valueOf(getAuthenticator().getLoggedUser()
							.getId()));
			paths.add(new RestPath(RestPath.PATH_REQUESTS, ""));

			List<RequestDto> requests = getRestServiceInvoker().call(paths, new GenericType<List<RequestDto>>() {
			});

			// Mapp :
			if (requests != null) {
				List<Request> toReturn = new ArrayList<Request>();
				for (RequestDto currentReq : requests) {
					Request req = getMapper().map(currentReq, Request.class);
					if (!req.isEmpty()) {
						toReturn.add(req);
					}
				}

				if (toReturn.size() == 0) {
					toReturn = null;
				}
				return toReturn;

			}
			return null;

		} catch (RestServiceException e) {
			return null;
		}

	}

	/**
	 * Delete a request.
	 */
	@Log
	void onActionFromDelete(long requestId) {

		try {

			List<RestPath> paths =
					RestPath.getSimplePath(RestPath.PATH_USERS, String.valueOf(getAuthenticator().getLoggedUser()
							.getId()));
			paths.add(new RestPath(RestPath.PATH_REQUESTS, String.valueOf(requestId)));

			this.getRestServiceInvoker().delete(paths);

			this.setActionMessageOk("request", ActionType.DELETE);

		} catch (RestServiceException e) {

		}

	}

}
